package com.cskaoyan.user.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import com.cskaoyan.user.utils.AesUtils;
import com.cskaoyan.user.utils.Md5Util;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author Aaliyah
 * @date 2022/9/21 10:55
 * @description: 对用户注册信息进行校验，并向用户注册表和用户验证表中插入记录
 */
@Service
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    IKaptchaService iKaptchaService;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public UserRetCode register(UserRegisterRequest userRegisterRequest, HttpServletRequest request) throws Exception {

        // 校验验证码是否正确    TODO 优化思路：使用服务调用的方法进行验证码校验
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(userRegisterRequest.getCaptcha());
        try {
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        } catch (ValidateException e) {
            e.printStackTrace();
            return UserRetCode.KAPTCHA_CODE_ERROR;
        }


        // 校验邮箱是否唯一
        Example emailExample = new Example(Member.class);
        emailExample.createCriteria().andEqualTo("email", userRegisterRequest.getEmail());
        List<Member> testEmail = memberMapper.selectByExample(emailExample);
        if (testEmail.size() != 0) {
            return UserRetCode.EMAIL_ALREADY_EXISTS;
        }


        // 校验账号是否唯一
        Example userNameExample = new Example(Member.class);
        userNameExample.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
        List<Member> testUsername = memberMapper.selectByExample(userNameExample);
        if (testUsername.size() != 0) {
            return UserRetCode.USERNAME_ALREADY_EXISTS;
        }


        Date date = new Date();

        // 向用户表中插入一条记录
        Member newMember = new Member();
        newMember.setUsername(userRegisterRequest.getUserName());
        newMember.setEmail(userRegisterRequest.getEmail());
        // 使用用户名为秘钥
        String encryptPassword = AesUtils.encrypt(userRegisterRequest.getUserPwd(), userRegisterRequest.getUserName());
        newMember.setPassword(encryptPassword);
        newMember.setCreated(date);
        newMember.setUpdated(date);
        try {
            memberMapper.insert(newMember);
        } catch (Exception e) {
            e.printStackTrace();
            return UserRetCode.USER_REGISTER_FAILED;
        }


        // 向用户验证表中插入一条记录
        UserVerify newUserVerify = new UserVerify();
        newUserVerify.setUsername(userRegisterRequest.getUserName());
        // 使用md5加密uuid
        String uid = UuidUtils.generateUuid();    // TODO creat uuid base on time
        String md5Uuid = Md5Util.getMd5(uid);
        newUserVerify.setUuid(md5Uuid);
        newUserVerify.setRegisterDate(date);
        newUserVerify.setIsVerify("N");
        newUserVerify.setIsExpire("N");
        try {
            userVerifyMapper.insert(newUserVerify);
        } catch (Exception e) {
            e.printStackTrace();
            return UserRetCode.USER_REGISTER_VERIFY_FAILED;
        }


        // 发送用户激活邮件 TODO 在子线程中运行
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2455404679@qq.com");
        message.setTo(userRegisterRequest.getEmail());
        message.setSubject("csmall商城激活");
        message.setText("http://localhost:8080/user/verify?uid=" + md5Uuid + "&username=" + userRegisterRequest.getUserName());
        javaMailSender.send(message);

        return UserRetCode.SUCCESS;
    }

    /**
     * @description: 获取系统当前时间
     * @date: 2022/9/21 12:23
     * @param: []
     */

    @Override
    public void verify(UserVerifyRequest request) {
        String uuid = request.getUuid();
        String username = request.getUsername();
        Example example = new Example(UserVerify.class);
        example.createCriteria().andEqualTo("uuid", uuid).andEqualTo("username", username);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        int affectRows = 0;
        for (UserVerify userVerify : userVerifies) {
            userVerify.setIsVerify("Y");
            affectRows = userVerifyMapper.updateByExampleSelective(userVerify,example);
        }

        //判断是否成功
        if (affectRows != 1) {
            throw new ValidateException(UserRetCode.USER_INFOR_UPDATE_FAIL.getCode(), UserRetCode.USER_INFOR_UPDATE_FAIL.getMessage());
        }
    }
}
